﻿@page "/"

@inject IJSRuntime jsRuntime;
<h1>Hello, world!</h1>


@using Newtonsoft.Json;
@using Newtonsoft.Json.Linq;
@using MLS.WasmCodeRunner
@code
{

private CodeRunner runner = new CodeRunner();

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    await base.OnAfterRenderAsync(firstRender);

    if (firstRender)
    {
    await jsRuntime.InvokeAsync<object>(
        "BlazorInterop.install",
        DotNetObjectReference.Create(this));

        await PostMessage(JObject.FromObject(new { ready = true }).ToString());
    }
}

    public ValueTask<string> PostMessage(string message)
    {
        // Implemented in interop.js
        return jsRuntime.InvokeAsync<string>
            ("BlazorInterop.postMessage", message);
    }

    [JSInvokable("MLS.Blazor.PostMessageAsync")]
    public async Task<string>
    PostMessageAsync(string message)
    {
        try
        {
            var result = runner.ProcessRunRequest(message);
            var logMsg = $"Computed {JObject.FromObject(result).ToString()}";
            await jsRuntime.InvokeAsync<string>("BlazorInterop.log", logMsg);

            if (result != null)
            {
            return JObject.FromObject(result).ToString();
            // await PostMessage(JObject.FromObject(result).ToString());
            }
            }
            catch
            {
            }

            return null;
        }
    }
}